package sale.wxb.loveshopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import sale.wxb.loveshopping.dao.SysUserDao;
import sale.wxb.loveshopping.entity.common.ResultException;
import sale.wxb.loveshopping.entity.convert.AddUserVoToSysUser;
import sale.wxb.loveshopping.entity.convert.SysUserVoToUpdateUserVo;
import sale.wxb.loveshopping.entity.model.SysUser;
import sale.wxb.loveshopping.entity.vo.RegisterVo;
import sale.wxb.loveshopping.entity.vo.common.PageListParam;
import sale.wxb.loveshopping.entity.vo.common.PageRecord;
import sale.wxb.loveshopping.entity.vo.user.AddUserVo;
import sale.wxb.loveshopping.entity.vo.user.SysUserVo;
import sale.wxb.loveshopping.entity.vo.user.UpdateUserVo;
import sale.wxb.loveshopping.service.ISysUserService;
import sale.wxb.loveshopping.utils.PageRecordUtil;
import sale.wxb.loveshopping.utils.SecurityUtil;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author 王小宝
 * @since 2022-09-02
 */
@Transactional
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements ISysUserService {
    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    @Value("${custom.default-password}")
    private String createDefaultPassword;

    @Override
    public SysUser getUser(SFunction<SysUser, ?> field, String value) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(field, value);
        // TODO 查询权限 只能查询权限级别比当前角色低的用户 超级管理员可以查询全部
        return this.getOne(queryWrapper);
    }

    @Override
    public SysUser getUserByToken() {
        return SecurityUtil.securityContextHolderGetSysUser();
    }

    @Override
    public SysUser getUserDetail(SysUser user) {
        return this.getById(user.getId());
    }

    @Override
    public SysUser getUserByAccount(String account) {
        return getUser(SysUser::getAccount, account);
    }

    @Override
    public SysUser getUserByEmail(String email) {
        return getUser(SysUser::getEmail, email);
    }

    @Override
    public SysUser getUserByPhone(String phone) {
        return getUser(SysUser::getEmail, phone);
    }

    @Override
    public PageRecord<SysUser> getListByPage(PageListParam param) {
        Page<SysUser> sysUserPage = new Page<>(param.getPage(), param.getSize());
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        // 设置查询参数
        queryWrapper.like(StringUtils.hasText(param.getKeyword()), SysUser::getUsername, param.getKeyword());
        return PageRecordUtil.toPageRecord(this.page(sysUserPage, queryWrapper));
    }

    @Override
    public Long createAccount(AddUserVo body, String initPassword) {
        if (getUserByAccount(body.getAccount()) != null) {
            throw new ResultException("该账号已被使用");
        }
        if (getUserByEmail(body.getEmail()) != null) {
            throw new ResultException("该邮箱已被使用");
        }

        SysUser user = AddUserVoToSysUser.INSTANCE.sourceToTarget(body);
        // 设置初始密码
        String password = StringUtils.hasText(initPassword) ? initPassword : bCryptPasswordEncoder.encode(createDefaultPassword);
        user.setPassword(password);

        if (!this.save(user)) {
            throw new ResultException("创建账号失败");
        }

        return user.getId();
    }

    @Override
    public Long createAccount(AddUserVo body) {
        return createAccount(body, "");
    }

    @Override
    public Long createAccount(RegisterVo body) {
        String pwd = bCryptPasswordEncoder.encode(body.getPassword());
        AddUserVo addUserVo = new AddUserVo();
        addUserVo.setAccount(body.getAccount());
        addUserVo.setSex((int) body.getSex());
        addUserVo.setEmail(body.getEmail());
        addUserVo.setUsername(body.getUsername());
        return createAccount(addUserVo, pwd);
    }

    @Override
    public Long updateUserById(UpdateUserVo body) {
        SysUser sysUser = this.getById(body.getId());

        if (ObjectUtils.isEmpty(sysUser)) {
            throw new ResultException("该用户不存在");
        }

        sysUser.setEnabled(body.getEnabled());
        sysUser.setAge(body.getAge());
        sysUser.setAvatar(body.getAvatar());
        sysUser.setSex(body.getSex().byteValue());
        sysUser.setUsername(body.getUsername());
        sysUser.setNickname(body.getNickname());

         if (!this.updateById(sysUser)) {
             throw new ResultException("保存更新失败");
         }

         return sysUser.getId();
    }

    @Override
    public Boolean updateUserByToken(SysUserVo body) {
        SysUser sysUser = SecurityUtil.securityContextHolderGetSysUser();
        UpdateUserVo updateUserVo = SysUserVoToUpdateUserVo.INSTANCE.sourceToTarget(body);
        updateUserVo.setEnabled(sysUser.getEnabled());
        updateUserVo.setId(sysUser.getId());
        return updateUserById(updateUserVo) > 0;
    }
}
